package org.conf4j.file.scaner;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.conf4j.Conf;
import com.conf4j.Conf4jConfigScanerConf;
import com.conf4j.PropInfo;
import com.conf4j.kit.ConfKit;
import com.conf4j.kit.StrKit;
import com.conf4j.kit.ValueKit;
import com.conf4j.scaner.ConfigScaner;

/**
 * 本地文件扫描器
 * 
 * @author dingnate
 *
 */
public class ConfigFileScaner extends ConfigScaner {
	private static transient final Logger LOG = LoggerFactory.getLogger(ConfigFileScaner.class);

	private String localPath;

	public ConfigFileScaner() {
		super(ValueKit.getValue(Conf4jConfigScanerConf.me.getIntervalSec(), 30L));
	}

	@Override
	protected boolean scan() {
		File dir = new File(getLocalPath());
		if (dir == null || !dir.exists() || !dir.isDirectory())
			return false;
		for (String key : getScanKeys()) {
			File file = new File(dir, key);
			if (file.exists() && file.isFile() && file.getName().toLowerCase().endsWith(".properties"))
				try {
					putScan(getKey(file), ConfKit.getVersion(file));
				} catch (IOException e) {
					LOG.error(e.getMessage(), e);
				}
		}
		return true;
	}

	/**
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private String getKey(File file) throws IOException {
		return file.getCanonicalPath().substring(getLocalPath().length() + 1);
	}

	@Override
	protected PropInfo getPropInfo(String key) {
		File file = new File(getLocalPath(), key);
		return new PropInfo(file);
	}

	@Override
	protected String[] getScanKeys() {
		return StrKit.split(ValueKit.getValue(Conf4jConfigScanerConf.me.getKeys(), ValueKit.EMPTY), Conf.SEPARATOR);
	}

	@Override
	protected String getLocalPath() {
		if (localPath != null)
			return localPath;
		localPath = Conf4jConfigScanerConf.me.getLocalPath();
		try {
			localPath = new File(localPath).getCanonicalPath();
		} catch (IOException e) {
			//do nothing
		}
		return localPath;
	}
}
